<?php


namespace App\Admin\Controllers\Chart;

use App\Admin\Controllers\Excel\InvoicesExport;
use App\Models\GoodsClassify;
use App\Models\OrderToGoods;
use Carbon\Carbon;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;
use Rap2hpoutre\FastExcel\Facades\FastExcel;
use Rap2hpoutre\FastExcel\SheetCollection;

/**
 * Created By FreeAbrams
 * Date: 2020/11/25
 * 菜品分析
 */
class GoodsChartController
{
	public function index(Content $content, Request $request)
	{
		$validate = Validator::make($request->all(), [
			'material_classify_id' => 'numeric']);
		if($validate->failed()){
			return false;
		}
		
		$data = $this->chart($request->all(['material_classify_id', 'startTime', 'endTime']));
		count($data);
		$rgb = 'rgba(254,90,0,1)';
		
		return $content
			->header('菜品分析')
			->row(view('admin.chart.goods.input', ['option' => GoodsClassify::all()->pluck('title', 'id')]))
			->row(view('admin.chart.goods.time-input'))
			->row(function (Row $row) use ($data){
				$row->column(10,view('admin.chart.goods.goods', ['name' => route('goodsChart'), 'data' => $data]));
			});
	}
	
	public function chart($request)
	{
		//dd($request);
		$timeStart = new Carbon();
		$timeEnd = new Carbon();
		$classify_id = '1';
		if(!empty($request['startTime'])){
			$timeStart = new Carbon($request['startTime']);
		}
		if(!empty($request['endTime'])){
			$timeEnd = new Carbon($request['endTime']);
		}
		if(!empty($request['material_classify_id'])){
			$classify_id = $request['material_classify_id'];
		}
		$timeBetween = [$timeStart->startOfYear(), $timeEnd->endOfYear()];
		
		$data = OrderToGoods::with(['goods' => function($q) use($classify_id){
			$q->withTrashed()->with(['classify' => function ($q) use($classify_id){
				$q->where('goods_classify_id', $classify_id)->withTrashed();
			}]);
		}])
			->where('print_order', 2)
			->whereBetween('created_at', $timeBetween)
			->get();
		
		$res = $data->groupBy('goods.name');
		
		$result = [];
		if(count($data)){
			foreach ($res as $k => $v)
			{
				$result[$k] = $v->sum('number');
			}
		}
		
		return $result;
	}
	
	public function export(Request $request)
	{
		//$i = new \App\Exports\InvoicesExport();
		//return Excel::download(new \App\Exports\InvoicesExport(), 'view.xlsx');
    	$validate = Validator::make($param, [
    		'startTime' => 'required',
    		'endTime' => 'required'
	    ]);
    	if($validate->failed()){
    		return false;
	    }
    	
    	$timeStart = new Carbon($param['startTime']);
    	$timeEnd = new Carbon($param['endTime']);
    	$timeBetween = [$timeStart->startOfDay(), $timeEnd->endOfDay()];
    	//dd($this->exportData($timeBetween));
		
    	return FastExcel::data($this->exportData($timeBetween))
					->download('会员.' . $timeStart->format('Y') . '年.xlsx');
	}
	
	public function exportData($timeBetween)
	{
		$goods =OrderToGoods::with(['goods' => function($q){
			$q->withTrashed()->with(['goodsToMaterials' => function($q) {
				$q->with(['purchaseToMaterials' => function($q){
					$q->orderBy('created_at', 'desc');
				}])->withPivot('number')
				;}]);
		}])->whereBetween('created_at', $timeBetween)
			->get();
		
		// 商品ID 分组 统计数量 数量 * 材料单价 * 材料用量 = 毛利润
		$goods->groupBy('goods_id');
		// 商品集合
		//		array =  [
		//		  "苏尔啤酒" => 10
		//		  "维尔威骑士（法国红）" => 8
		//		  "台湾贝拉活生蚝" => 5
		//		  "名厨鲜切片鹅肝" => 2
		//		]
		//dd($goods->groupBy('goods_id'));
		foreach ($goods->groupBy('goods_id') as $k => $v)
		{
			// 卖出的商品数量
			static $goodsCollection = [];
			// 毛利润
			static $goodsPrice = [];
			$goodsCollection[$v[0]->goods->name] = $v->count('number');
			$goodsPrice[$v[0]->goods->name] = 0;
			$goodsNum = $goodsCollection[$v[0]->goods->name];
			// 商品材料用量
			static $goodsMaterialCost = [];
			foreach ($v as $key => $val){
				$goodsToMaterials = $val->goods->goodsToMaterials;
				$number = 0;
				$unit_price = 0;
				foreach ($goodsToMaterials as $value)
				{
					$number = $value->pivot->number;
					$unit_price = $value->purchaseToMaterials;
					
					//dd($goodsNum, $value->purchaseToMaterials->sum('sell'), $value->purchaseToMaterials[0]->unit_price);
					// 判断用料是否已经超过第一批库存生成商品数 = 第一批库存毛利 + 第二批毛利 + 第三..
					foreach ($value->purchaseToMaterials as $purchase) {
						$price = 0;
						if($goodsNum - $purchase->sell > 0){
							$price += $purchase->sell * $purchase->unit_price;
							$goodsNum = $goodsNum - $purchase->sell;
						} else {
							$price += $goodsNum * $purchase->unit_price;
							
							$goodsPrice[$v[0]->goods->name] = $price;
							break;
						}
					}
					//dd($goodsNum, $value->purchaseToMaterials[0]->unit_price, $goodsPrice);
				}
				//dd($val->goods, $val->goods->goodsToMaterials);
				// 材料用量
			}
			
			//$goodsMaterialCost[$v[0]->goods->name];
		}
		// 计算时如果售出量超出某一批次 单价采用下一批次
		//dd($goods->groupBy('goods_id'), $goodsCollection, $goodsPrice);
		//dd($goods->groupBy('goods_id'), $goodsCollection);
		//dd($goodsPrice);
		// 分类
		$goodsClassify = GoodsClassify::with(['goods' => function($q){
			$q->select('name');
		}])->get();
		
		$items = [];
		foreach ($goodsClassify as $v){
			foreach ($v->goods as $value){
				//dd($v->title,$value);
				if(isset($goodsPrice[$value->name])){
					$items[$v->title][$value->name] = collect([$value->name =>  $goodsPrice[$value->name]]);
					
				}
			}
		}
		//dd(collect($items));
		if(isset($goodsPrice)){
			//dd($goodsPrice);
			return $list = new SheetCollection($items);
		} else {
			return $list = new SheetCollection([]);
		}
	}
}